package com.ehl.capture.data;

import com.ehl.capture.bean.CarBean;
import com.ehl.capture.bean.CarPlaBean;
import com.ehl.capture.bean.WatchBean;
import com.ehl.capture.db.Config;
import com.ehl.capture.db.DBProxy;
import com.ehl.capture.db.DBProxyBean;
import com.ehl.capture.kafka.KafkaConsumer;
import com.ehl.capture.webservice.AxisProxyClient;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.log4j.Logger;

public class PassCarConnectWebserviceCommon
        implements IPassCar
{
    private static final String separator = "=";
    private static final String empty = "";
    private static final String FILE_SEPARATOR = "/";
    public static List<WatchBean> kkTransitionData = Collections.synchronizedList(new ArrayList());
    public static Map<String, String> cloudIdToKkid = new HashMap();
    private static Logger logger = Logger.getLogger(PassCarConnectWebserviceCommon.class);
    private static final String TZTP_UPLOAD_URL = Config.getValue("tztp.upload.url");
    private static final Boolean TZTP_UPLOAD_FLAG = Boolean.valueOf(Boolean.parseBoolean(Config.getValue("tztp.upload.flag")));
    private static final Boolean PIC_CONVERT_FLAG = Boolean.valueOf(Boolean.parseBoolean(Config.getValue("pic.convert.flag")));
    public static Map<String, String> zw2gaw = new HashMap();
    private static final Boolean FILTER_NOPLATE_FLAG = Boolean.valueOf(Boolean.parseBoolean(Config.getValue("is.filter.noplate")));
    private static final Boolean TP2_UPLOAD_FLAG = Boolean.valueOf(Boolean.parseBoolean(Config.getValue("if.tp2.upload")));
    private static final Boolean TP3_UPLOAD_FLAG = Boolean.valueOf(Boolean.parseBoolean(Config.getValue("if.tp3.upload")));
    private static final Boolean FILTER_DELAYRECORD_FLAG = Boolean.valueOf(Boolean.parseBoolean(Config.getValue("if.filter.delayedRecord")));
    private static final int DELAYED_RECORD_TIME = Integer.parseInt(Config.getValue("filter.delaytime"));
    private static final String TPLJ_KEYWORDS = Config.getValue("tplj.prefix.keywords");
    private static final boolean UPLOAD_FLAG = Boolean.parseBoolean(Config.getValue("enable.imagedata.upload"));
    private static final String FTP_UPLOAD_MODE = Config.getValue("ftp.upload.mode");
    private static final boolean ZDDD_CHECK_FLAG = Boolean.parseBoolean(Config.getValue("zdkk.redischeck.flag"));

    static {
        if (UPLOAD_FLAG){
            //initFTP();
        }
        reloadTranserTgs();
        logger.info("===end load watch data===========");
        String sqlKkid = "select cloud_id,kkid from T_ITGS_TGSINFO where cloud_id is not null and kkid is not null";
        Object[][] listKk = DBProxy.getMultiResult(sqlKkid);

        if (listKk != null) {
            for (int i = 0; i < listKk.length; ++i) {
                String key = listKk[i][0].toString();
                String zw_gaw = listKk[i][1].toString();
                cloudIdToKkid.put(key, zw_gaw);
            }
        }

        String pic_gawip_cc = Config.getValue("pic_gawip_cc");
        String[] zw_gaw_arr = pic_gawip_cc.split(",");
        String[] gawArr = zw_gaw_arr;
        int len = zw_gaw_arr.length;

        for (int i = 0; i < len; ++i) {
            String zw_gaw = gawArr[i];
            zw2gaw.put(zw_gaw.split("-")[0], zw_gaw.split("-")[1]);
        }
    }

    private static void initFTP() {
        /*logger.info("=================初始化ftp服务=======");
        try {
            List<String> ftps = Config.getPrefixedPropertyValue("ftp.list");
            Iterator var2 = ftps.iterator();

            while(var2.hasNext()) {
                String ftp = (String)var2.next();
                String[] ftpfields = ftp.split(",");
                String[] prefixDirs = (String[])Arrays.copyOfRange(ftpfields, 3, ftpfields.length);
                FtpInfo ftpInfo = new FtpInfo(ftpfields[0], ftpfields[1], ftpfields[2], prefixDirs);
                FTPMananger.addFtpInfo(ftpInfo);
            }

            FtpPool.init();
        } catch (Exception var6) {
            var6.printStackTrace();
            logger.error("ftp初始化失败", var6);
        }
        logger.info("=================ftp服务初始化成功=======");*/
    }

    private static void reloadTranserTgs()
    {
        String sql = "select * from T_WXS_WATCH";
        List list = DBProxyBean.queryList(sql, WatchBean.class, "db");
        logger.info("===start load watch data===========");
        kkTransitionData.clear();
        if (list != null)
            for (int i = 0; i < list.size(); ++i) {
                Object obj = list.get(i);
                if (obj instanceof WatchBean) {
                    logger.info(createConvertLogString((WatchBean)obj));
                    kkTransitionData.add((WatchBean)obj);
                }
            }
    }

    /**
     * 仅打印日志
     * @param obj
     * @return
     */
    private static Object createConvertLogString(WatchBean obj) {
        StringBuilder sb = new StringBuilder();
        sb.append("xh:").append(obj.getXh()).append(" ehl:").append(obj.getFxckkid()).append("-").append(obj.getFxckkmc()).append("-").append(obj.getFxcfx())
                .append(" wxs:").append(obj.getKkbh()).append("-").append(obj.getFxlx()).append(" cdh:").append(obj.getCdh());
        return sb.toString();
    }

    private String getKKid(String key) {
        String value = cloudIdToKkid.get(key);
        return value == null ? "" : value;
    }

    public CarPlaBean strToBean(String content) {
        if (StringUtils.isNotEmpty(content)) {
            String[] list = content.split("\n");
            if (list != null) {
                return this.handBean(list);
            }
        }
        return null;
    }

    public void handData(CarPlaBean plaBean) {
        try {
            long startTime = System.currentTimeMillis();
            Random random = new Random();
            int randomCode = random.nextInt(1000);
            if (plaBean == null) {
                return;
            }

            if ((FILTER_DELAYRECORD_FLAG.booleanValue()) && (isDelayed(plaBean.getPasstime()))) {
                logger.info("过滤超时记录!passtime is:" + plaBean.getPasstime());
                return;
            }

            if ((FILTER_NOPLATE_FLAG.booleanValue()) && (plaBean.getCarplate().trim().equals("无牌"))) {
                logger.info("过滤无牌车！");
                return;
            }

            CarBean bean = plaBeanToCarBean(plaBean);
            logger.info("接到过车数据：" + bean.getGcsj() + "~" + bean.getKkbh() + "~" + bean.getHphm() + "~" + bean.getHpzl() + "~" + bean.getTplj() + "~" + bean.getTp1());

            transition(bean);
            if (StringUtils.isBlank(bean.getKkbh())) {
                return;
            }

            if (UPLOAD_FLAG) {
                if ((plaBean.getImgid1() == null) || (plaBean.getImgid1().isEmpty())) {
                    logger.error("过车数据：" + plaBean.getCarplate() + "~" + plaBean.getTgsid() + "~" + plaBean.getPasstime() + "~" + plaBean.getPlatetype() + " 图片数据为空！");
                    return;
                }

                uploadImage(bean);
            }

            if (ZDDD_CHECK_FLAG) {
                ZdkkService.chekcZdkkOverTime(bean);
            }

            CarBean tztpBean = (CarBean)bean.clone();
            if (PIC_CONVERT_FLAG.booleanValue()) {
                bean.setTplj(zwtogaw(bean.getTplj()));
            }

            sendCarResult(bean, tztpBean);
            logger.info("code:" + randomCode + " time3:" + (System.currentTimeMillis() - startTime));
        } catch (Exception var8) {
            var8.printStackTrace();
            logger.error("处理时错误    ", var8);
        }
    }

    private void uploadImage(CarBean bean) throws Exception {
        /*try {
            EHLFtpClient ftp = FtpPool.getFtpClientInMode(FTP_UPLOAD_MODE);
            byte[] imageData = getImageFileData(bean.getTplj() + bean.getTp1());
            String ftpImageUrl = ftp.uploadFile(imageData, this.getChildDir(bean), this.getImageName(bean));
            logger.info("上传图片成功，" + ftpImageUrl + " 号牌:" + bean.getHphm());
            bean.setTplj(this.parseTplj(ftpImageUrl));
            bean.setTp1(this.split(ftpImageUrl));
            bean.setTp2("");
            bean.setTp3("");
        } catch (Exception var8) {
            if (ftp != null) {
                FtpPool.invalidateFtpClient(ftp);
                throw var8;
            }

            logger.error("上传ftp图片失败", var8);
        } finally {
            if (ftp != null) {
                FtpPool.closeFtp(ftp);
            }
        }*/
    }

    private String getChildDir(CarBean bean) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat toSd = new SimpleDateFormat("yyyyMMdd");

        try {
            String passTime = toSd.format(sd.parse(bean.getGcsj()));
            return passTime + "/" + bean.getKkbh();
        } catch (ParseException var5) {
            var5.printStackTrace();
        }
        return null;
    }

    private String getImageName(CarBean carBean) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat toSd = new SimpleDateFormat("yyyyMMddHHmmss");

        try {
            Random random = new Random();
            int randomCode = random.nextInt(100);
            String passTime = toSd.format(sd.parse(carBean.getGcsj()));
            return passTime + "_" + randomCode + ".jpg";
        } catch (ParseException var7) {
            var7.printStackTrace();
            return null;
        }
    }

    private void sendCarResult(CarBean bean, CarBean tztpBean) {
        boolean sendResult = AxisProxyClient.sendCar(bean);
        if ((TZTP_UPLOAD_FLAG.booleanValue()) && (sendResult))
            uploadTzImage(tztpBean);
    }

    private boolean isDelayed(String passtime)throws ParseException {
        Date delayedDate = DateUtils.addSeconds(new Date(), 0 - DELAYED_RECORD_TIME);
        logger.info("delayedDate:" + delayedDate.toLocaleString() + " " + passtime);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date passDate = sd.parse(passtime);
        return passDate.before(delayedDate);
    }

    public String zwtogaw(String picpath) {
        if ((picpath != null) && (!"".equals(picpath))) {
            String[] arr = picpath.split("//");
            String ip = arr[1].split("/")[0];
            String gawip = (String)zw2gaw.get(ip);
            if (StringUtils.isEmpty(gawip)) {
                return picpath;
            }
            picpath = picpath.replaceAll(ip, gawip);
            return picpath;
        }

        return "";
    }

    private static void uploadTzImage(CarBean bean)
    {
        byte[] fileData = getImageFileData(bean);
        if (fileData.length <= 0) {
            logger.error("特征图片上传失败！");
        } else {
            OutputStream pw = null;
            BufferedReader br = null;
            InputStream is = null;
            try{
                String tztpUpdateUrl = createTztpUpdateUrl(bean);
                URL url = new URL(tztpUpdateUrl);
                HttpURLConnection huc = (HttpURLConnection)url.openConnection();
                huc.setRequestProperty("content-type", "text/html");
                huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
                huc.setRequestProperty("Content-Length", String.valueOf(fileData.length));
                huc.setDoOutput(true);
                huc.setDoInput(true);
                huc.setRequestMethod("POST");
                huc.setConnectTimeout(2000);
                pw = huc.getOutputStream();
                pw.write(fileData);
                pw.flush();
                pw.close();
                is = huc.getInputStream();
                br = new BufferedReader(new InputStreamReader(is));
                String content = "";

                for (String line = br.readLine(); line != null; line = br.readLine()) {
                    content = content + line;
                }

                logger.info("上传图片响应内容" + content);
                logger.info("上传特征图片成功:" + bean.toString());
                return;
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("上传特征图片失败！", e);
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException var25) {
                        var25.printStackTrace();
                        logger.error("输入流关闭失败", var25);
                    }
                }

                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException var24) {
                        var24.printStackTrace();
                        logger.error("is输入流关闭失败", var24);
                    }
                }

                if (pw != null)
                    try {
                        pw.close();
                    } catch (IOException var23) {
                        var23.printStackTrace();
                        logger.error("输出流关闭失败", var23);
                    }
            }
        }
    }

    private static byte[] getImageFileData(String imagePath)
    {
        InputStream bis = null;
        ByteArrayOutputStream bos = null;
        byte[] var8;
        try
        {
            URL imageUrl = new URL(imagePath);
            URLConnection myurlcon = imageUrl.openConnection();
            myurlcon.setConnectTimeout(5000);
            myurlcon.setReadTimeout(5000);
            bis = myurlcon.getInputStream();
            bos = new ByteArrayOutputStream();
            int len;
            while ((len = bis.read()) > -1)
            {
                bos.write(len);
            }

            byte[] fileData = bos.toByteArray();
            return fileData;
        } catch (Exception var18) {
            var18.printStackTrace();
            logger.error(imagePath, var18);
            var8 = new byte[0];
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException var19) {
                    var19.printStackTrace();
                    logger.error(imagePath.toString(), var19);
                }
            }

            if (bis != null)
                try {
                    bis.close();
                } catch (IOException var18) {
                    var18.printStackTrace();
                    logger.error(imagePath, var18);
                }
        }
        return var8;
    }

    private static byte[] getImageFileData(CarBean bean) {
        return getImageFileData(bean.getTplj() + bean.getTztp());
    }

    private static String createTztpUpdateUrl(CarBean bean) {
        try {
            StringBuffer sb = new StringBuffer();
            sb.append(TZTP_UPLOAD_URL)
                    .append("&kkbh=").append(bean.getKkbh())
                    .append("&fxlx=").append(bean.getFxlx())
                    .append("&cdh=").append(bean.getCdh())
                    .append("&hphm=").append(URLEncoder.encode(bean.getHphm(), "UTF-8"))
                    .append("&gcsj=").append(URLEncoder.encode(bean.getGcsj(), "UTF-8"));
            logger.info("upload tztp:" + sb.toString());
            return sb.toString();
        } catch (UnsupportedEncodingException var3) {
            var3.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        try {
            //initFTP();
            CarBean plaBean = new CarBean();
            plaBean.setTplj("http://n.sinaimg.cn/news/20170307/");
            plaBean.setTp1("unMU-fycapec2697574.jpg");
            plaBean.setKkbh("1");
            plaBean.setGcsj("2");
            plaBean.setFxlx("3");
            PassCarConnectWebserviceCommon instance = new PassCarConnectWebserviceCommon();
            //instance.uploadImage(plaBean);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

    }

    private CarBean plaBeanToCarBean(CarPlaBean plaBean) {
        CarBean bean = new CarBean();
        if (plaBean.getTgsid() == null) {
            return null;
        } else {
            bean.setXh(plaBean.getTgsid() + UUID.randomUUID().toString());
            bean.setKkbh(plaBean.getTgsid());
            bean.setFxlx(plaBean.getDrivedir());
            bean.setCdh(plaBean.getDriveway());
            bean.setHphm(plaBean.getCarplate());
            if (bean.getHphm() == null || bean.getHphm().trim().equals("")
                    || bean.getHphm().indexOf("无牌") > -1 || bean.getHphm().indexOf("未识别") > -1 || bean.getHphm().indexOf("无法识别") > -1) {
                bean.setHphm("-");
            }

            bean.setHpzl(plaBean.getPlatetype().length() == 1 ? "0" + plaBean.getPlatetype() : plaBean.getPlatetype());
            if (StringUtils.isEmpty(bean.getHpzl()) || bean.getHpzl().equals("99")) {
                bean.setHpzl("44");
            }

            if (StringUtils.isNotEmpty(plaBean.getPasstime()) && plaBean.getPasstime().length() >= 19) {
                bean.setGcsj(plaBean.getPasstime().substring(0, 19));
            }

            bean.setClsd(plaBean.getSpeed());
            bean.setClxs("0");
            bean.setHpys(plaBean.getPlatecolor());
            if (StringUtils.isEmpty(bean.getHpys())) {
                bean.setHpys("9");
            }

            this.setImg(plaBean, bean);
            return bean;
        }
    }

    private void setImg(CarPlaBean plaBean, CarBean bean) {
        String tplj = "";
        String tp1 = plaBean.getImgid1();
        if (!plaBean.isFlg()) {
            tplj = this.parseTplj(tp1);
            bean.setTp1(this.split(plaBean.getImgid1()));
            bean.setTp2(this.split(plaBean.getImgid2()));
            bean.setTp3(this.split(plaBean.getImgid3()));
            bean.setTztp(this.createTztpUrl(plaBean));
            bean.setTplj(tplj);
            if (!TP2_UPLOAD_FLAG) {
                bean.setTp2("");
            }

            if (!TP3_UPLOAD_FLAG) {
                bean.setTp3("");
            }
        } else {
            bean.setTp1("");
            bean.setTp2("");
            bean.setTp3("");
            bean.setTplj(tp1);
        }

    }

    private String parseTplj(String tp) {
        if (StringUtils.isEmpty(tp)) {
            return "";
        } else if (StringUtils.isNotEmpty(TPLJ_KEYWORDS)) {
            return tp.substring(0, tp.lastIndexOf(TPLJ_KEYWORDS) + TPLJ_KEYWORDS.length() + 1);
        } else {
            return tp.lastIndexOf("/") > 0 ? tp.substring(0, tp.lastIndexOf("/") + 1) : "";
        }
    }

    private String createTztpUrl(CarPlaBean plaBean) {
        return !StringUtils.isEmpty(plaBean.getImgid2()) && !"null".equals(plaBean.getImgid2()) ? this.split(plaBean.getImgid2()) : this.split(plaBean.getImgid3());
    }

    private String split(String tp) {
        if (StringUtils.isEmpty(tp)) {
            return "";
        } else if (StringUtils.isNotEmpty(TPLJ_KEYWORDS)) {
            return tp.substring(tp.lastIndexOf(TPLJ_KEYWORDS) + TPLJ_KEYWORDS.length() + 1);
        } else {
            return tp.lastIndexOf("/") > 0 ? tp.substring(tp.lastIndexOf("/") + 1, tp.length()) : "";
        }
    }

    private CarPlaBean handBean(String[] list) {
        CarPlaBean plaObj = null;
        try {
            plaObj = CarPlaBean.class.newInstance();
            Method[] methods = CarPlaBean.class.getMethods();
            Method[] methodsArr = methods;
            int len = methods.length;

            for(int i = 0; i < len; ++i) {
                Method method = methodsArr[i];
                String[] var11 = list;
                int var10 = list.length;

                for(int var9 = 0; var9 < var10; ++var9) {
                    String str = var11[var9];
                    String name = str.split("=", 2)[0];
                    String value = str.split("=", 2).length <= 1 ? "" : str.split("=", 2)[1];
                    if (method.getName().toUpperCase().indexOf(name) > 0 && method.getReturnType() == Void.TYPE) {
                        method.invoke(plaObj, value == null ? "" : value);
                    }
                }
            }
        } catch (Exception var14) {
            var14.printStackTrace();
        }
        return plaObj;
    }

    private void transition(CarBean bean) {
        if (bean == null) {
            bean.setKkbh("");
        } else {
            boolean flg = true;
            if (kkTransitionData != null) {
                for(int i = 0; i < kkTransitionData.size(); i++) {
                    WatchBean obj = kkTransitionData.get(i);
                    if (this.getKKid(bean.getKkbh()).equals(obj.getFxckkid())
                            && bean.getCdh().equals(obj.getCdh())
                            && bean.getFxlx().equals(obj.getFxcfx())) {
                        bean.setKkbh(obj.getKkbh());
                        bean.setFxlx(obj.getFxlx());
                        bean.setCdh(obj.getCdh());
                        flg = false;
                        break;
                    }
                }
            }

            if (flg) {
                logger.error("获取数据对应关系失败：从kafka获取的卡口id转换成kkid(对应无锡所字段fxckkid)：" + getKKid(bean.getKkbh()) + ";从kafka获取的车道数(对应无锡所字段cdh)：" + bean.getCdh() + ";从kafka获取的方向(对应无锡所字段fxcfx)：" + bean.getFxlx());
                bean.setKkbh("");
            }
        }
    }

    public void setUrl(CarPlaBean bean, String partition, long offset) {
        if (StringUtils.isNotEmpty(bean.getImgid1()) && !bean.getImgid1().toLowerCase().startsWith("http://") && !bean.getImgid1().toLowerCase().startsWith("ftp://")) {
            bean.setImgid1(KafkaConsumer.picpath + bean.getImgid1());
        }

        if (bean.getImgid2() != null && !"null".equals(bean.getImgid2()) && !"".equals(bean.getImgid2()) && !bean.getImgid2().toLowerCase().startsWith("http://") && !bean.getImgid2().toLowerCase().startsWith("ftp://")) {
            bean.setImgid2(KafkaConsumer.picpath + bean.getImgid2());
        }

        if (bean.getImgid3() != null && !"null".equals(bean.getImgid3()) && !"".equals(bean.getImgid3()) && !bean.getImgid3().toLowerCase().startsWith("http://") && !bean.getImgid3().toLowerCase().startsWith("ftp://")) {
            bean.setImgid3(KafkaConsumer.picpath + bean.getImgid3());
        }

    }

    public void updateWatchBean(WatchBean bean)
    {
        if (bean != null) {
            bean.setYzbj("1");
            StringBuffer buf = new StringBuffer();
            String sql = "update t_wxs_watch t set t.yzbj='1' where t.xh=?";
            List list = new ArrayList();
            list.add(bean.getXh());
            boolean flg = DBProxy.execute("db", sql, list);
            if (!flg) {
                buf.setLength(0);
                buf.append("更新无锡所卡口序号" + bean.getXh() + "  ,");
                buf.append("卡口编号" + bean.getKkbh() + "  ,");
                buf.append("方向" + bean.getFxlx() + "  ,");
                buf.append("车道" + bean.getCdh() + "  ,");
                logger.error(buf.toString());
            } else {
                logger.info("更新无锡所卡口状态成功：" + bean.getKkbh() + "~" + bean.getFxlx() + "~" + bean.getCdh());
            }
        }
    }


}